package top.honlnk.common.interceptor;

import cn.hutool.core.util.StrUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import top.honlnk.common.exception.CustomException;
import top.honlnk.service.UserService;

import java.util.Objects;

@Slf4j
@Component
public class SubmitIdInterceptor  implements HandlerInterceptor{

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {
        // 1. 获取请求头中的submitId
        String submitId = request.getHeader("submitId");
        // 获取请求参数中的submitId
        if (StrUtil.isBlank(submitId)) {
            submitId = request.getParameter("submitId");
        }
        // 2. 判断是否为空，或者非法
        if (StrUtil.isBlank(submitId)) {
            String path = request.getRequestURI();
            log.info("path:{}", path);
            if (Objects.equals(path, "/api/user/update_table")) {
                throw new CustomException("无submitId，小盆友，一定要带上自己的submitId再来修改课程表哦！");
            }
            if (Objects.equals(path, "/api/user/get_table")) {
                throw new CustomException("无submitId，小盆友，一定要带上自己的submitId再来获取课程表哦！");
            }
            if (Objects.equals(path, "/api/admin/del_user_table")) {
                throw new CustomException("无submitId，请选择一个你要删除的用户的课程表！");
            }
        }
        // 3. 获取key中的信息
        log.info("key:{}", submitId);
        // 检查submitID是否有效
        userService.validateSubmitId(submitId);
        return true;
    }
}
